package com.rich.common.util;

import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @Author:fei
 * @Date:2021/8/19
 */
public class HttpUtil {
    public static String sendHttpRequest(String httpURL, Map<String,String> parms) throws Exception {
        URL url = new URL(httpURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        if (parms!=null && parms.size()>0){
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String,String> param :parms.entrySet()){
                sb.append("&").append(param.getKey()).append("=").append(param.getValue());
            }
            connection.getOutputStream().write(sb.substring(1).toString().getBytes("UTF-8"));
        }

        connection.connect();
        String response = StreamUtils.copyToString(connection.getInputStream(), Charset.forName("UTF-8"));
        return response;
    }
}
